﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Collections;
using Portal.Web.Model;
using Portal.Web.Utility;
using Portal.Exam.Model;
using Portal.Exam.Bussiness;
using Portal.Core;

namespace Portal.Exam.Render
{
    public class ViewResultExamStudent
    {
        public static AjaxOut Draw(string SiteId, bool ShowPrintButton)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                string ExamRoomStudentId = (string)WebEnvironments.Request(SiteId, "ExamRoomStudentId");

                //string tid = (string)WebEnvironments.Request(SiteId, "tid");
                //ExamRoomStudentCls CurrentStudent = new ExamRoomStudentBll().CreateModel(SiteId, tid);

                //if(CurrentStudent.ExamRoomStudentId != ExamRoomStudentId)
                //    throw new Exception(ExamUltility.AccessDenied);

                ExamRoomStudentCls OExamRoomStudent = new ExamRoomStudentBll().CreateModel(SiteId, ExamRoomStudentId);
                if (OExamRoomStudent == null) throw new Exception("Tham số không hợp lệ!");

                StringBuilder RetHtml = new StringBuilder();
                string Status = ExamUltility.ExamWaiting;
                DataTable dtExamRoomStudent = new ExamRoomStudentBll().ReadingExamRoomStudentByStudentCode(SiteId, ExamRoomStudentId);                                                

                if (dtExamRoomStudent.Rows.Count > 0)
                {
                    int FinishExam = (int)dtExamRoomStudent.Rows[0]["FinishExam"];
                    DateTime StartExam = new System.DateTime();
                    if (dtExamRoomStudent.Rows[0]["StartExam"] != DBNull.Value)
                    {
                        StartExam = (DateTime)dtExamRoomStudent.Rows[0]["StartExam"];
                    }
                    if (StartExam != new System.DateTime())
                    {
                        if (FinishExam == 0)
                        {
                            Status = ExamUltility.ExamDoing;
                        }
                        else
                        {
                            Status = ExamUltility.ExamDone;
                        }
                    }
                }

                if (Status.Equals(ExamUltility.ExamWaiting))
                {
                    RetHtml.Append("<div class=CssWarning>" + ExamUltility.AccessDenied + "</div>\r\n");
                    OAjaxOut.HtmlContent = RetHtml.ToString();
                    return OAjaxOut;
                }

                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonUrl = WebConfig.GetButtonIconRoot(OSiteParam);
                if (ShowPrintButton)
                {
                    RetHtml.Append(
                        " <div class=DatabaseFunction>\r\n" +
                        "        <ul>\r\n" +
                        "            <li onclick=\"javascript:window.open('PrintResultExamStudent.aspx?ExamRoomStudentId=" + ExamRoomStudentId + "','_blank');\"><img class=image src=\"" + ButtonUrl + "/Print.png\"><div>In bài làm</div></li>\r\n" +
                        "            <li onclick=\"javascript:window.open('ListFinishedExamStudent.aspx?ExamRoomId=" + OExamRoomStudent.ExamRoomId + "','_self');\"><img class=image src=\"" + ButtonUrl + "/back.png\"><div>Quay lại</div></li>\r\n" +
                        "        </ul>\r\n" +
                        "  </div>\r\n");
                }
                string ExamTemplateType = OExamRoomStudent.ExamTemplateType;
                string DonePoint = OExamRoomStudent.DonePoint.ToString();

                if (ExamTemplateType.ToLower().Equals("freetext"))
                {
                    DonePoint = "";
                }

                RetHtml.Append(
                    " <div class=CssHeading>Kết quả bài làm - " + OExamRoomStudent.StudentCode + " / " + OExamRoomStudent.StudentName + " / Số điểm: &nbsp" + DonePoint + "/" + OExamRoomStudent.TotalPoint + "</div>\r\n" +
                    " <div class=CssExamInfo>" + OExamRoomStudent.ExamTitle + "</div>\r\n" +
                    " <div class=CssExamContent>\r\n" +
                    " <ul>\r\n");

                DataTable dtExamQuestion = new ExamQuestionBll().ReadingExamQuestion(SiteId, ExamRoomStudentId);
                for (int iIndex = 0; iIndex < dtExamQuestion.Rows.Count; iIndex++)
                {
                    string ExamQuestionId = (string)dtExamQuestion.Rows[iIndex]["ExamQuestionId"];
                    string Type = (string)dtExamQuestion.Rows[iIndex]["Type"];
                    if (!Type.ToLower().Equals("freetext"))
                    {
                        DonePoint = OExamRoomStudent.DonePoint + "/" + OExamRoomStudent.TotalPoint;
                    }
                    RetHtml.Append("  <li>" + DrawOneQuestion(SiteId, dtExamQuestion, iIndex, ExamRoomStudentId, ExamQuestionId).HtmlContent + "</li>\r\n");
                }
                RetHtml.Append("</ul>\r\n" +
                         "</div>\r\n");
                OAjaxOut.HtmlContent = RetHtml.ToString();
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }


        public static AjaxOut DrawOneQuestion(
            string SiteId,
            DataTable dtExamQuestion,
            int QuestionIndex,
            string ExamRoomStudentId,
            string ExamQuestionId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string Html = "";
                string Title = (string)dtExamQuestion.Rows[QuestionIndex]["Title"];
                string Question = (string)dtExamQuestion.Rows[QuestionIndex]["Question"];
                string Type = (string)dtExamQuestion.Rows[QuestionIndex]["Type"];
                string StudentAnswer = dtExamQuestion.Rows[QuestionIndex]["StudentAnswer"] != null ? (string)dtExamQuestion.Rows[QuestionIndex]["StudentAnswer"] : "";
                int QuestionCorrectAnswer = int.Parse(dtExamQuestion.Rows[QuestionIndex]["CorrectAnswer"].ToString());
                string StudentAnswerText = ExamUltility.NotAnswer;

                if (QuestionCorrectAnswer == 1)
                    StudentAnswerText = ExamUltility.CorrectAnswer;
                else
                    StudentAnswerText = ExamUltility.WrongAnswer;

                Html += "<div class=CssQuestionTitle>" + (QuestionIndex + 1) + ". " + Title + "</div>\r\n";
                if (!string.IsNullOrEmpty(Question))
                {
                    Html += "<div class=CssQuestion>" + Question + "</div>\r\n";
                }
                DataTable dtAnswer = new ExamQuestionBll().ReadingExamAnswer(SiteId, ExamQuestionId);


                if (Type.ToLower().Equals("YesNo".ToLower()))
                {
                    string CorrectAnswer = (string)dtAnswer.Rows[0]["CorrectAnswer"];
                    Html += "<div class=CssQuestionType>Câu hỏi đúng sai</div>\r\n";
                }

                //******************bestanswer******************
                if (Type.ToLower().Equals("bestanswer"))
                {
                    Html += "<div class=CssQuestionType>Câu hỏi chọn 1 phương án đúng</div>\r\n" +
                            "<div class=CssListAnswer>\r\n" +
                            "<ul>\r\n";

                    for (int iIndex = 0; iIndex < dtAnswer.Rows.Count; iIndex++)
                    {
                        string CssCorrectAnswer = "";
                        string ExamAnswerId = (string)dtAnswer.Rows[iIndex]["ExamAnswerId"];
                        string AnswerText = (string)dtAnswer.Rows[iIndex]["AnswerTextFirst"];
                        string CorrectAnswer = (string)dtAnswer.Rows[iIndex]["CorrectAnswer"];
                        string Checked = "";
                        if (ExamAnswerId.Equals(StudentAnswer))
                        {
                            Checked = "[X]";
                        }
                        if (CorrectAnswer.Equals("YES"))
                        {
                            CssCorrectAnswer = "class=CssCorrectAns";
                        }
                        Html += "   <li>" + Checked + " <span " + CssCorrectAnswer + ">" + AnswerText + "</span></li>\r\n";
                    }
                    Html +=
                        "</ul>\r\n" +
                        "</div>\r\n";
                }
                //******************multichoice******************
                if (Type.ToLower().Equals("multichoice"))
                {
                    string[] ItemAnswerd = StudentAnswer.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    ArrayList ArrayListCorrectItemAnswer = new ArrayList();

                    Html += "<div class=CssQuestionType>Câu hỏi chọn nhiều phương án</div>\r\n" +
                            "<div class=CssListAnswer>\r\n" +
                            "<ul>\r\n";

                    for (int iIndex = 0; iIndex < dtAnswer.Rows.Count; iIndex++)
                    {
                        string CssCorrectAnswer = "";
                        string ExamAnswerId = (string)dtAnswer.Rows[iIndex]["ExamAnswerId"];
                        string AnswerText = (string)dtAnswer.Rows[iIndex]["AnswerTextFirst"];
                        string CorrectAnswer = (string)dtAnswer.Rows[iIndex]["CorrectAnswer"];
                        string Checked = "";
                        for (int iCheck = 0; iCheck < ItemAnswerd.Length; iCheck++)
                        {
                            if (ExamAnswerId.Equals(ItemAnswerd[iCheck]))
                            {
                                Checked = "[X]";
                                break;
                            }
                        }
                        if (CorrectAnswer.Equals("YES"))
                        {
                            CssCorrectAnswer = "class=CssCorrectAns";
                        }
                        Html += "   <li>" + Checked + " <span " + CssCorrectAnswer + ">" + AnswerText + "</span></li>\r\n";
                    }
                    Html +=
                        "</ul>\r\n" +
                        "</div>\r\n";
                }
                if (Type.ToLower().Equals("truefalse".ToLower()))
                {
                    //doan nay lay thong so tra loi
                    string Header = "  <tr><td></td><td class=\"tdFirstColAnswer\"><b>Sinh viên trả lời</b></td><td class=\"tdSecondColAnswer\"><b>Câu trả lời đúng</b></td></tr>";
                    string[] ItemAnswerd = StudentAnswer.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    ArrayList ArrayListCorrectItemAnswer = new ArrayList();

                    Html += "<div class=CssQuestionType>Câu hỏi chọn phương án đúng sai</div>\r\n" +
                            "<div class=CssListAnswer>\r\n" +
                             "<table class=cssUlAnswerText>" +
                             Header;

                    for (int iIndex = 0; iIndex < dtAnswer.Rows.Count; iIndex++)
                    {
                        string CssCorrectAnswer = "";
                        string tExamAnswerId = (string)dtAnswer.Rows[iIndex]["ExamAnswerId"];
                        string tAnswerTextFirst = (string)dtAnswer.Rows[iIndex]["AnswerTextFirst"];
                        bool CheckMarked = false;
                        for (int iIndexCheck = 0; iIndexCheck < ItemAnswerd.Length; iIndexCheck++)
                        {
                            if (ItemAnswerd[iIndexCheck].Trim().Length > 0)
                            {
                                if (ItemAnswerd[iIndexCheck].Equals(tExamAnswerId))
                                {
                                    CheckMarked = true;
                                }
                            }
                        }

                        string tCorrectAnswer = (string)dtAnswer.Rows[iIndex]["CorrectAnswer"];
                        string StudyAns = string.Empty;
                        string TrueAns = string.Empty;
                        if (StudentAnswer.TrimEnd().Length > 0)
                        {
                            if (CheckMarked)
                            {
                                StudyAns = "Đúng";
                            }
                            else
                            {
                                StudyAns = "Sai";
                            }
                        }
                        else
                        {
                            StudentAnswer = ExamUltility.StudentNotAnswer;
                        }
                        if (tCorrectAnswer.Equals("YES"))
                        {
                            CssCorrectAnswer = "class=CssCorrectAns";
                            TrueAns = "[Đúng]";
                        }
                        else
                        {
                            TrueAns = "[Sai]";
                        }
                        Html += "  <tr><td " + CssCorrectAnswer + ">" + tAnswerTextFirst + "</span></td><td class=\"tdFirstColAnswer\">" + StudyAns + "</td><td class=\"tdSecondColAnswer\">" + TrueAns + "</td></tr>";
                    }
                    Html +=
                        "</table>" +
                        "</div>\r\n";
                }

                string Value = ExamUltility.StudentNotAnswer;

                if (Type.ToLower().Equals("crosslink".ToLower()))
                {
                    //doan nay lay thong so tra loi

                    DataTable dtItemsPA2 = new ExamQuestionBll().ReadingExamAnswerByAnswerTextLast(SiteId, ExamQuestionId);
                    string[] Answers = StudentAnswer.Split(new char[] { '|' });// 1:8BEBC1CB-C33B-4990-ACB4-E570A3DD4A85|2:41BF0513-91A6-49BA-B973-C73C0C34E27D|3:9B3345AC-7319-4A08-AB9B-8061A610EBAE|                    
                    string Header =
                                "  <tr>" +                        
                                "       <td class=\"tdCrossAnswer1\"></td>" +                        
                                "       <td class=\"tdFirstColAnswer\"><b>Sinh viên trả lời</b></td>" +
                                "       <td class=\"tdSecondColAnswer\"><b>Câu trả lời đúng</b></td>" +
                                "       <td class=\"tdCrossAnswer2\"></td>" +
                                "  </tr>";
                    Html += "<div class=CssQuestionType>Câu hỏi cross link</div>\r\n" +
                            "<div class=CssListAnswer>\r\n" +
                            "<table class=cssUlAnswerText>" +
                            Header;

                    string[] ItemAnswerd = StudentAnswer.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    ArrayList ArrayListCorrectItemAnswer = new ArrayList();


                    for (int iIndex = 0; iIndex < dtAnswer.Rows.Count; iIndex++)
                    {
                        string tExamAnswerId = (string)dtAnswer.Rows[iIndex]["ExamAnswerId"];
                        string tAnswerTextFirst = (string)dtAnswer.Rows[iIndex]["AnswerTextFirst"];

                        string pa2AnswerTextFirst = (string)dtItemsPA2.Rows[iIndex]["AnswerTextLast"];
                        string pa2ExamAnswerId = (string)dtItemsPA2.Rows[iIndex]["ExamAnswerId"];


                        int tCorrectAnswer = int.Parse(dtItemsPA2.Rows[iIndex]["IndexOrder"].ToString());

                        if (Answers.Length > 0)
                        {
                            for (int iIndexCheck = 0; iIndexCheck < Answers.Length; iIndexCheck++)
                            {
                                if (Answers[iIndexCheck].IndexOf(":") != -1) //1:8BEBC1CB-C33B-4990-ACB4-E570A3DD4A85
                                {
                                    string[] AnswersPA2 = Answers[iIndexCheck].Split(new char[] { ':' });

                                    if (AnswersPA2[1].Trim().Length > 0)
                                    {
                                        if (AnswersPA2[1].ToLower().Equals(pa2ExamAnswerId.ToLower()))
                                        {
                                            Value = AnswersPA2[0];
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        Html +=
                           "  <tr>" +
                           "       <td class=\"tdCrossAnswer1\">" + (iIndex + 1) + "." + tAnswerTextFirst + "</td>" +
                           "       <td class=\"tdFirstColAnswer\">" + Value + "</td>" +
                           "       <td class=\"tdSecondColAnswer\">[" + tCorrectAnswer + "]</td>" +
                           "       <td class=\"tdCrossAnswer2\">" + pa2AnswerTextFirst + "</td>" +
                           "  </tr>";
                    }
                    Html +=
                        "</table>" +
                        "</div>\r\n";
                }

                if (Type.ToLower().Equals("image".ToLower()))
                {
                    //doan nay lay thong so tra loi

                    DataTable dtItemsPA2 = new ExamQuestionBll().ReadingExamAnswerByAnswerTextLast(SiteId, ExamQuestionId);
                    string[] Answers = StudentAnswer.Split(new char[] { '|' });// 1:8BEBC1CB-C33B-4990-ACB4-E570A3DD4A85|2:41BF0513-91A6-49BA-B973-C73C0C34E27D|3:9B3345AC-7319-4A08-AB9B-8061A610EBAE|                    
                    string Header =
                                "  <tr>" +
                                "       <td class=\"tdCrossAnswer1\">Câu hỏi</td>" +
                                "       <td class=\"tdFirstColAnswer\"><b>Sinh viên trả lời</b></td>" +
                                "       <td class=\"tdSecondColAnswer\"><b>Câu trả lời đúng</b></td>" +
                                "       <td class=\"tdCrossAnswer2\">Câu trả lời</td>" +
                                "  </tr>";

                    string QuestionId = (string)dtItemsPA2.Rows[0]["CorrectAnswer"];

                    string ImageFileName = (string)dtItemsPA2.Rows[0]["ImageFileName"];

                    SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                    string HttpDataRoot = Portal.Web.Utility.WebConfig.HttpDataRoot(OSiteParam);
                    HttpDataRoot = HttpDataRoot + "/Cms/" + WebSessionUtility.GetCurrentLoginUser().AssetCode + "/" + QuestionId;
                    string ImageUrl = string.Empty;
                    if (!string.IsNullOrEmpty(ImageFileName))
                    {
                        ImageUrl = HttpDataRoot + "/" + ImageFileName;
                    }

                    Html += "<div class=CssQuestionType>Câu hỏi hình ảnh</div>\r\n" +
                            "<div class=CssListAnswer>\r\n" +
                            "<table class=cssUlAnswerText>" +
                            "<th colspan=4><image src='" + ImageUrl + "' class='imgexam' /></td>" +
                            Header;

                    string[] ItemAnswerd = StudentAnswer.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    ArrayList ArrayListCorrectItemAnswer = new ArrayList();


                    for (int iIndex = 0; iIndex < dtAnswer.Rows.Count; iIndex++)
                    {
                        string tExamAnswerId = (string)dtAnswer.Rows[iIndex]["ExamAnswerId"];
                        string tAnswerTextFirst = (string)dtAnswer.Rows[iIndex]["AnswerTextFirst"];

                        string pa2AnswerTextLast = (string)dtItemsPA2.Rows[iIndex]["AnswerTextLast"];
                        string pa2ExamAnswerId = (string)dtItemsPA2.Rows[iIndex]["ExamAnswerId"];


                        int tCorrectAnswer = int.Parse(dtItemsPA2.Rows[iIndex]["IndexOrder"].ToString());


                        for (int iIndexCheck = 0; iIndexCheck < Answers.Length; iIndexCheck++)
                        {
                            if (Answers[iIndexCheck].IndexOf(":") != -1) //1:8BEBC1CB-C33B-4990-ACB4-E570A3DD4A85
                            {
                                string[] AnswersPA2 = Answers[iIndexCheck].Split(new char[] { ':' });

                                if (AnswersPA2[1].Trim().Length > 0)
                                {
                                    if (AnswersPA2[1].ToLower().Equals(pa2ExamAnswerId.ToLower()))
                                    {
                                        Value = AnswersPA2[0];
                                        break;
                                    }
                                }
                            }
                        }

                        Html +=
                               "  <tr>" +
                               "       <td class=\"tdCrossAnswer1\">" + (iIndex + 1) + "." + tAnswerTextFirst + "</td>" +
                               "       <td class=\"tdFirstColAnswer\">" + Value + "</td>" +
                               "       <td class=\"tdSecondColAnswer\">[" + tCorrectAnswer + "]</td>" +
                               "       <td class=\"tdSecondColAnswer\">" + pa2AnswerTextLast + "</td>" +
                               "  </tr>";
                    }
                    Html +=
                        "</table>" +
                        "</div>\r\n";
                }
                string CssAnswerStatus = " class=CssAnswerStatus";
                if (Type.ToLower().Equals("freetext"))
                {
                    Html += "<div class=CssListAnswer>\r\n" +
                                StudentAnswer +
                            "</div>";
                    StudentAnswerText = string.Empty;
                    CssAnswerStatus = string.Empty;
                }

                Html += "<br/><div " + CssAnswerStatus + ">" + StudentAnswerText + "</div>\r\n";
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }

    }
}
